﻿module tweetc.TweetStatus

open System
open System.Net
open System.Text
open System.IO
open System.Runtime.Serialization
open System.Runtime.Serialization.Json
open System.Globalization

[<DataContract>]
type User = {
    [<field:DataMember(Name="followers_count")>] Followers:int
    [<field:DataMember(Name="screen_name")>] ScreenName:string
    [<field:DataMember(Name="name")>] Name:string
    [<field:DataMember(Name="id_str")>] Id:int
    [<field:DataMember(Name="location")>] Location:string }

[<DataContract>]
type Tweet = {
    [<field:DataMember(Name="id_str")>] Id:string
    [<field:DataMember(Name="text")>] Text:string
    [<field:DataMember(Name="retweeted")>] IsRetweeted:bool
    [<field:DataMember(Name="created_at")>] DateStr:string
    [<field:DataMember(Name="user", IsRequired=false)>] User:User
    [<field:DataMember(Name="sender", IsRequired=false)>] Sender:User
    [<field:DataMember(Name="source")>] Source:string
    mutable Index:int }

let twitterDateFormat = "ddd MMM dd HH:mm:ss zzz yyyy"; //"Fri Oct 07 18:41:13 +0000 2011"
let toDateTime s = DateTime.ParseExact(s, twitterDateFormat, CultureInfo.InvariantCulture)

let parseTweets (tweets:string) =
    let json = new DataContractJsonSerializer(typeof<Tweet[]>)
    let byteArray = System.Text.Encoding.UTF8.GetBytes(tweets)
    use stream = new MemoryStream(byteArray)
    json.ReadObject(stream) :?> Tweet[]

[<DataContract>]
type SearchResult = {
    [<field:DataMember(Name="id_str")>] Id:string
    [<field:DataMember(Name="created_at")>] DateStr:string
    [<field:DataMember(Name="source")>] Source:string
    [<field:DataMember(Name="text")>] Text:string
    [<field:DataMember(Name="from_user")>] Name:string }
          
[<DataContract>]
type Search = {
    [<field:DataMember(Name="refresh_url")>] RefreshUrl:string
    [<field:DataMember(Name="results")>] Results:SearchResult[] }

let parseSearch (search:string) =
    let json = new DataContractJsonSerializer(typeof<Search>)
    let byteArray = System.Text.Encoding.UTF8.GetBytes(search)
    use stream = new MemoryStream(byteArray)
    json.ReadObject(stream) :?> Search

    